package com.zrm.zfcrpa.configuration.security;

import com.zrm.zfcrpa.utils.MyJwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class MyTokenAuthFilter extends BasicAuthenticationFilter {

    private static final String MOBILE_LOGIN="/authMobile/login";

    private static final String EXPIRETION_URL = "/MyExpiretionHandler";

    public MyTokenAuthFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if(!StringUtils.isBlank(token) ){
            try {
            String username = MyJwtUtils.getUserName(token);
            String role  = MyJwtUtils.getRole(token);
            List<SimpleGrantedAuthority> list = Arrays.asList(new SimpleGrantedAuthority(role));
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username,null,list));
            }catch (Exception e){
                request.setAttribute("msg","请求头异常");
                request.setAttribute("e","请求头错误或已过期");
                request.getRequestDispatcher(EXPIRETION_URL).forward(request,response);
            }
          }
        super.doFilterInternal(request,response,chain);
    }

}
